package com.RLFZ.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.RLFZ.entity.User;
import com.RLFZ.service.UserService;
import com.RLFZ.vo.DataView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 用于上传头像
 * @author 86166
 */
@Controller
@RequestMapping("file")
@Slf4j
public class FileController {

    @Autowired
    private UserService userService;

    // 设置最大文件大小为5MB

    private static final long AVATAR_MAX_SIZE = 1024*500;

    @ResponseBody
    @PostMapping("/uploadFile")
    public DataView uploadFile(@RequestParam("file") MultipartFile file,
                                           HttpServletRequest request, HttpSession session){
        log.warn("/file/uploadFile - {}",file);
        DataView dataView=new DataView();
        //空文件验证
        if(file.isEmpty()){
            dataView.setMsg("上传文件异常！文件不能为空！");
        }
        //文件大小
        long fileSize = file.getSize();
        if(fileSize>AVATAR_MAX_SIZE){
            dataView.setMsg("文件上传异常！文件大小超过上限："+(AVATAR_MAX_SIZE/1024)+"kb");
        }

        //生成文件名 --> 直接使用uuid+文件后缀
        String oFilename = file.getOriginalFilename();
        Integer index = oFilename.lastIndexOf(".");
        String suffix = "";
        if(index!=-1){
            suffix = oFilename.substring(index);
        }
        String filename = UUID.randomUUID().toString()+suffix;

        // 11/11 start
        //生成目标路径
        String filePath = request.getServletContext().getRealPath("upload");
        System.err.println("....."+filePath);


        //生成目标路径
//        String filePath = request.getServletContext().getRealPath("E:\\图片\\test-image\\");
//        String filePath = "D:\\ZHBS\\RLFZ\\src\\main\\resources\\static\\images";
//        System.err.println("....."+filePath);

        // 11/11 end
        File parent = new File(filePath);
        if(!parent.exists()){
            parent.mkdirs();
        }

        File dest = new File(parent,filename);

        //将用户上传的头像保存在服务器
        try {
            file.transferTo(dest);
        }catch (IllegalStateException e){
            dataView.setMsg("文件上传异常！");
        }catch (IOException e){
            dataView.setMsg("文件上传异常！");
        }


        //将头像在服务器的路径保存在数据库
//        String img = "/images/"+filename;
        String img = "/upload/"+filename;
        User user = (User) session.getAttribute("user");
        //修改于11.4  start
     //   session.setMaxInactiveInterval(0);

        //11.4  end

        user.setImg(img);
        session.setAttribute("user",user);
        userService.updateById(user);
        dataView.setMsg(img);
        return dataView;
    }

    @ResponseBody
    @PostMapping("/uploadFile1")
    public DataView uploadFile1(@RequestParam("file") MultipartFile file,
                               HttpServletRequest request, HttpSession session) throws IOException {
        log.warn("/file/uploadFile - {}",file);
        DataView dataView=new DataView();
        //空文件验证
        if(file.isEmpty()){
            dataView.setMsg("上传文件异常！文件不能为空！");
        }
        //文件大小
        long fileSize = file.getSize();
        if(fileSize>AVATAR_MAX_SIZE){
            dataView.setMsg("文件上传异常！文件大小超过上限："+(AVATAR_MAX_SIZE/1024)+"kb");
        }

        //生成文件名 --> 直接使用uuid+文件后缀
        String oFilename = file.getOriginalFilename();
        Integer index = oFilename.lastIndexOf(".");
        String suffix = "";
        if(index!=-1){
            suffix = oFilename.substring(index);
        }
        String filename = UUID.randomUUID().toString()+suffix;

        byte[] bytes = file.getBytes();


        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tGyD4nvevVk9aoz5WP5";
        String accessKeySecret = "1nbrhnGWBuJeJNJsx2PPYV0Jq6hqQi";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "zbrnb";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "2023/3/23/"+filename;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 填写字符串。
            String content = "Hello OSS，你好世界";
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
                    objectName, new ByteArrayInputStream(bytes));
            putObjectRequest.setProcess("true");
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 如果上传成功，则返回200。
            System.out.println(result.getResponse().getStatusCode());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }





        //将头像在服务器的路径保存在数据库
//        String img = "/images/"+filename;
//        String img = "/upload/"+filename;
//        String img="https://zbrnb.oss-cn-hangzhou.aliyuncs.com/01fc7b88-348d-4f87-86a5-031b71958b30.jpeg";
        String img="https://zbrnb.oss-cn-hangzhou.aliyuncs.com/"+objectName;
        User user = (User) session.getAttribute("user");
        //修改于11.4  start
        //   session.setMaxInactiveInterval(0);

        //11.4  end

        user.setImg(img);
        session.setAttribute("user",user);
        userService.updateById(user);
        dataView.setMsg(img);
        return dataView;
    }

    /**
     * 获取用户头像
     * @return
     */
//    @RequestMapping("/showImageByPath")
//    @ResponseBody
//    public DataView showImageByPath(){
//        DataView dataView=new DataView();
//        return dataView;
//    }



}
